﻿using System;
using System.IO;
using System.Reflection;

namespace WikiMaml.Console
{
    public class Program
    {
        private static void Main(string[] args)
        {
            Arguments arguments = Arguments.Parse(args);

            if (arguments.DisplayHelp)
            {
                PrintHelp();
                Environment.ExitCode = -1;
                return;
            }

            var logger = new ConsoleLogger();
            var translator = new Translator(new RenderingEngine(), new FileService(), logger);
            string sourceFullPath, outputFullPath;

            try
            {
                sourceFullPath = Path.GetFullPath(arguments.SourceFolder);
                outputFullPath = Path.GetFullPath(arguments.OutputFolder);
            }
            catch (ArgumentException)
            {
                PrintHelp();
                Environment.ExitCode = -2;
                return;
            }

            if (!translator.Translate(Directory.GetFiles(sourceFullPath, arguments.SourceFilePattern, SearchOption.AllDirectories), sourceFullPath, outputFullPath))
            {
                logger.LogError("Failed to write all output from {0} to {1}", arguments.SourceFolder, arguments.OutputFolder);
                Environment.ExitCode = -2;
            }
            else
            {
                logger.LogMessage("Wrote html files to {0}", arguments.OutputFolder);
                Environment.ExitCode = 0;
            }
        }

        private static void PrintHelp()
        {
            string executableName = Path.GetFileNameWithoutExtension(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath);

            System.Console.WriteLine();
            System.Console.WriteLine("usage: {0} [options] <sourceFolder> <outputFolder>", executableName);
            System.Console.WriteLine();
            System.Console.WriteLine("Valid options:");
            System.Console.WriteLine("   /p:<filePattern>         The file pattern to search source files");
            System.Console.WriteLine("   /pattern:<filePattern>   by. The default is *.waml");
            System.Console.WriteLine();
        }

    }
}
